import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  TextInput,
  Platform,
  TouchableOpacity,
  TouchableHighlight,
  View,
  Modal,
  ListView
} from 'react-native';
//说明：
//this.props.flag：true :不关联选项     false:级联
//this.props.data: 数据

//this.props.textContent:选择框提示
//titleText:标题   titleTextStyle：标题样式
//contextStyle:选项样式
//horizontalLineStyle：分隔线样式
//buttonStyle:按钮样式
//buttonText：按钮文本样式
//cellStyle:每一列样式
//dataStyle:每一行文本样式
//_onResult():返回被选中项的下标
//_this.props.onConfirm():'确定'调用此方法
import CheckBox from 'react-native-checkbox';
let _this;
let flag = true;//true :不关联选项     false:级联
let option = '请选择'//默认提示
export default class Test extends Component {
    constructor(props, context) {
        super(props, context);
        this.state = {
            dataSource: [],
            show: false,
            isCheck: false,
            textContent: this.props.textContent,
            result: [],
            data:[]
        };
        ds = new ListView.DataSource({
          rowHasChanged: (r1, r2) => r1 !== r2,
        });
        flag = this.props.flag;
        this.state.data = this.props.data;

        this._onInitData();

        _this = this;
    }
    //初始化数据
    _onInitData(){
      if (flag) {
          // data = this.props.data
          for (let i = 0; i < this.state.data.length; i++) {
            //默认选中每列第一项
            this.state.result[i] = 0;
            this.state.dataSource.push(ds.cloneWithRows(this._updateShow(this.state.data[i], i, 0)));
          }
        } else {//级联
          // data = this.props.data
          for (let i = 0; i < this.state.data.length; i++) {
            this.state.result[i] = 0;
            //this.onShowData(data[i], i)每一列默认选项
            this.state.dataSource.push(ds.cloneWithRows(this._updateShow(this.onShowData(this.state.data[i], i), i, 0)));
          }
        }
    }
    // _showRows(data, ins) {
    //   let rows = [];
    //   for (let i = 0; i < data.length; i++) {
    //     rows.push({ text: data[i], index: ins, isCheck: false })
    //   }
    //   return rows;
    // }
    //更新rowID行为选择状态
    _updateShow(data, ins, rowID) {
      let rows = [];
      for (let i = 0; i < data.length; i++) {
        if (i == rowID) {
          rows.push({ text: data[i], index: ins, isCheck: true })
        } else {
          rows.push({ text: data[i], index: ins, isCheck: false })
        }
      }
      return rows;
    }
    //传入新数据
    _onNewData(data){
      this.setState({
          textContent:this.props.textContent
      })
      this.state.dataSource = [];
      this.state.data = data;
      this._onInitData();
    }
    //更新每列选项
    _onUpdate(index, rowID) {
      //index  当前列
      //next下一列
      let next = index + 1;

      try {
        if (flag) {
            this.state.dataSource[index] = ds.cloneWithRows(this._updateShow(this.state.data[index], index, rowID));
        } else {
          if (next == this.state.dataSource.length) {
            //更新当前列（被点击列）
            this.state.dataSource[index] = ds.cloneWithRows(this._updateShow(this.onShowData(this.state.data[index], index), index, rowID));
          } else {
            //更新当前列（被点击列）
            this.state.dataSource[index] = ds.cloneWithRows(this._updateShow(this.onShowData(this.state.data[index], index), index, rowID));
            //更新下一级
            if (this.state.data[next] != null) {
              this.state.dataSource[next] = ds.cloneWithRows(this._updateShow(this.onShowData(this.state.data[next], next), next, -1));
            } else {
              alert('无数据')
            }
          }
          //后面列默认选项
          if (next < this.state.dataSource.length) {
            for (let i = next; i < this.state.dataSource.length; i++) {
              this.state.result[i] = 0;
              let l = this.onShowData(this.state.data[i], i);
              this.state.dataSource[i] = (ds.cloneWithRows(this._updateShow(l, i, this.state.result[i])));
            }
          }
        }
        this.setState({
          dataSource: this.state.dataSource
        })
      } catch (e) {
        console.error('无数据');
      }
    }
    //更新当前列 
    // _onUpdateCurrent(index,){
    //   this.state.dataSource[index] = ds.cloneWithRows(this._updateShow(this.onShowData(data[index], index), index, rowID));
    // }
    //获取下一列选项
    onShowData(data, index) {
      let newData = data;
      if (index > 0) {
        for (let i = 0; i < index; i++) {
          if (newData[this.state.result[i]] != null && newData[this.state.result[i]].length > 0) {
            newData = newData[this.state.result[i]];
          } else {
            this.state.result[index] = -1;
            return ['无选项'];
          }
        }
      }
      return newData;
    }
    _renderRow(rowData, sectionID, rowID, highlightRow) {
      if (rowData.isCheck == true) {
        return (
          <TouchableHighlight onPress={() => {
            _this.state.result[rowData.index] = rowID;
            _this._onUpdate(rowData.index, rowID);
          } }>
            <View>
              <Text numberOfLines={1} style={[styles.data, styles.checkedStyle, _this.props.dataStyle]}>
                {rowData.text}
              </Text>
            </View>
          </TouchableHighlight>
        )
      } else {
        return (
          <TouchableHighlight onPress={() => {
            _this.state.result[rowData.index] = rowID;
            _this._onUpdate(rowData.index, rowID);
          } }>
            <View>
              <Text numberOfLines={1} style={[styles.data, _this.props.dataStyle]}>
                {rowData.text}
              </Text>
            </View>
          </TouchableHighlight>
        )
      }
    }
    //每行下面加分割线
    _renderSeparator(sectionID, rowID, adjacentRowHighlighted) {
      return (
        <View key={`{sectionID}-${rowID}`}
          style={{ height: 0.5, backgroundColor: 'black' }}>
        </View>
      );
    }
    _showContext() {
      let context = [];
      for (let i = 0; i < this.state.dataSource.length; i++) {
        context.push(
          <View key={'listview' + i} style={[styles.cell, _this.props.cellStyle]}>
            <ListView
              dataSource={this.state.dataSource[i]}
              renderRow={this._renderRow}
              //renderSeparator={this._renderSeparator}//分隔线
              //style={styles.cell}
              showsVerticalScrollIndicator={false}//不显示滚动条
              />
          </View>
        )
      }
      return context;
    }
    onResult() {
      //alert(JSON.stringify(result))
      _this.setState({
        show: false
      })
      return _this.state.result;
    }
    //确定
    onConfirm() {
      _this.setState({
        result: _this.state.result,
      })
      let showData = [];
      _this.props.onConfirm();
      //显示在选择框中
      for (let i = 0; i < _this.state.data.length; i++) {
        if (flag) {
          showData[i] = _this.state.data[i][_this.state.result[i]];
        } else {
          let l = _this.onShowData(_this.state.data[i], i)[_this.state.result[i]];
          if (l != null) {
            showData[i] = l;
          }
        }
      }
      // alert(JSON.stringify(showData))
      _this.setState({
        textContent: showData.join('')
      })
    }
    //取消
    _cancle() {
      _this.setState({
        show: false,
      })
    }
    onShow() {
      _this.setState({
        show: true,
      })
      
    }
    render() {
      return (
        <View>
          <Modal
            animationType={'slide'}
            transparent={true}
            visible={this.state.show}
            onShow={() => { } }
            onRequestClose={() => this.onRequestClose()} >
            <View style={styles.container}>
              <View style={styles.subView}>

                <Text style={[styles.titleText, this.props.titleTextStyle]}>
                  {this.props.titleText ? this.props.titleText : '请选择'}
                </Text>
                <View style={[styles.horizontalLine, this.props.horizontalLineStyle]} />
                <View style={[styles.context, this.props.contextStyle]}>
                  {this._showContext()}
                </View>

                <View style={[styles.horizontalLine, this.props.horizontalLineStyle]} />
                <View style={styles.buttonView}>
                  <TouchableOpacity underlayColor='transparent'
                    style={styles.buttonStyle}
                    onPress={_this._cancle}>
                    <Text style={styles.buttonText}>
                      取消
                    </Text>
                  </TouchableOpacity>
                  <View style={styles.verticalLine} />
                  <TouchableOpacity underlayColor='transparent'
                    style={styles.buttonStyle}
                    onPress={this.onConfirm}>
                    <Text style={styles.buttonText}>
                      确定
                    </Text>
                  </TouchableOpacity>
                </View>
              </View>
            </View>
          </Modal>
          <TouchableOpacity onPress={() => {_this = this;this.onShow()} }>
            <View style={[styles.textContentStyle, this.props.textContentStyle]}>
              <Text numberOfLines={1}>{this.state.textContent}</Text>
            </View>
          </TouchableOpacity>
        </View>

      );
    }
}

const styles = StyleSheet.create({
  container: {
    backgroundColor: '#00000099',
    alignItems: 'center',
    justifyContent: 'center',
    flex: 1,
  },
  // modal上子View的样式  
  subView: {
    backgroundColor: '#ffffff',
    alignSelf: 'stretch',
    justifyContent: 'center',
    borderWidth: 0.5,
    borderColor: '#ccc',
    position: 'absolute',
    bottom: 1,
    right: 0.1,
    left: 0.1
  },
  // 标题  
  titleText: {
    marginTop: 5,
    marginBottom: 5,
    fontSize: 16,
    fontWeight: 'bold',
    textAlign: 'center',
  },
  // 水平的分割线  
  horizontalLine: {
    height: 0.5,
    backgroundColor: '#ccc',
  },
  // 按钮  
  buttonView: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  buttonStyle: {
    flex: 1,
    height: 34,
    alignItems: 'center',
    justifyContent: 'center',
  },
  // 竖直的分割线  
  verticalLine: {
    width: 0.5,
    height: 34,
    backgroundColor: '#ccc',
  },
  buttonText: {

    fontSize: 16,
    color: '#3393F2',
    textAlign: 'center',
  },
  textContentStyle: {
    borderWidth: 1,
    borderColor: '#12b7f5',
    borderRadius: 3,
    height: 30,
    justifyContent: 'center',
    alignItems: 'center',
  },
  //选项
  context: {
    flexDirection: 'row',
    maxHeight: 200,
  },
  //选项的每一列
  cell: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    maxHeight: 200,
  },
  //选项每一列的每一行
  data: {
    fontSize: 13,
    textAlign: 'center',
    margin: 10
  },
  //选项选中后
  checkedStyle: {
    color: "#12b7f5"
  }
});

